//
//  DefaultViewController.m
//  APJ Resource
//
//  Created by Richard Zhao on 1/21/14.
//  Copyright (c) 2014 APJ. All rights reserved.
//

#import "DefaultViewController.h"
#import "syncDataService.h"
#import "Staff.h"
#import "webService.h"
#import "LoginViewController.h"
#import "SimpleBarChart.h"
#import "HRStore.h"
#import "ResourceRequirement.h"
#import "Dept.h"

@interface DefaultViewController ()

@end

@implementation DefaultViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Main" image:[UIImage imageNamed:@"icon_home"] tag:0];
        [self setTabBarItem:item];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]]];
    
    UISwipeGestureRecognizer *gestureLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(next:)];
    [gestureLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:gestureLeft];
    
    UISwipeGestureRecognizer *gestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(prev:)];
    [gestureRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:gestureRight];
}

- (void)prev:(UISwipeGestureRecognizer *)gesture
{
    NSDateComponents* cmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
    cmpnts.month -= 1;
    _currentMonth = [[NSCalendar currentCalendar] dateFromComponents:cmpnts];
    [self bindDateForChart];
}

- (void)next:(UISwipeGestureRecognizer *)gesture
{
    NSDateComponents* cmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
    cmpnts.month += 1;
    _currentMonth = [[NSCalendar currentCalendar] dateFromComponents:cmpnts];
    [self bindDateForChart];
}



- (void)viewDidAppear:(BOOL)animated
{
    extern BOOL isLogin;
    if (!isLogin) {
        LoginViewController *login = [[LoginViewController alloc] init];
        [self presentViewController:login animated:YES completion:nil];
    }  else {
        [self SetupChart];
        [self bindDateForChart];
    }
}

- (void)bindDateForChart
{
    if (!_deptList) {
        _deptList = [[HRStore sharedStore] allDept];
    }
    if (!_reqSumList) {
        _reqSumList = [[NSMutableArray alloc] init];
    } else {
        [_reqSumList removeAllObjects];
    }
    if (!_currentMonth) {
        _currentMonth = [NSDate date];
    }
    
    for (int i=0; i<_deptList.count; i++) {
        NSArray *reqs = [[HRStore sharedStore] reqByDept:[(Dept *)[_deptList objectAtIndex:i] deptId]
                                                 inMonth:[_currentMonth timeIntervalSince1970]];
        int sum = 0;
        for (ResourceRequirement *req in reqs) {
            sum += req.count;
        }
        [_reqSumList addObject:[NSNumber numberWithInt:sum]];
    }
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MMM YYYY"];
    monthLabel.text = [format stringFromDate:_currentMonth];
    [_chart reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)SetupChart
{
	_barColors						= @[[UIColor blueColor], [UIColor redColor], [UIColor blackColor], [UIColor orangeColor], [UIColor purpleColor], [UIColor greenColor]];
	_currentBarColor				= 0;
	CGRect chartFrame				= CGRectMake(10,100,1000.0,400.0);
	_chart							= [[SimpleBarChart alloc] initWithFrame:chartFrame];
	//_chart.center					= CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 5);
	_chart.delegate					= self;
	_chart.dataSource				= self;
	_chart.barShadowOffset			= CGSizeMake(2.0, 1.0);
	_chart.animationDuration		= 1.0;
	_chart.barShadowColor			= [UIColor grayColor];
	_chart.barShadowAlpha			= 0.5;
	_chart.barShadowRadius			= 1.0;
	_chart.barWidth					= 18.0;
	_chart.xLabelType				= SimpleBarChartXLabelTypeHorizontal;
	_chart.incrementValue			= 1;
	_chart.barTextType				= SimpleBarChartBarTextTypeTop;
	_chart.barTextColor				= [UIColor whiteColor];
	_chart.gridColor				= [UIColor grayColor];
    
	[self.view addSubview:_chart];
    
    monthLabel = [[UILabel alloc] init];
    monthLabel.frame = CGRectMake(40, 30, 200, 50);
    monthLabel.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [self.view addSubview:monthLabel];
}

#pragma mark SimpleBarChartDataSource

- (NSUInteger)numberOfBarsInBarChart:(SimpleBarChart *)barChart
{
	return _deptList.count;
}

- (CGFloat)barChart:(SimpleBarChart *)barChart valueForBarAtIndex:(NSUInteger)index
{
	return [[_reqSumList objectAtIndex:index] floatValue];
}

- (NSString *)barChart:(SimpleBarChart *)barChart textForBarAtIndex:(NSUInteger)index
{
	return [[_reqSumList objectAtIndex:index] stringValue];
}

- (NSString *)barChart:(SimpleBarChart *)barChart xLabelForBarAtIndex:(NSUInteger)index
{
	return [(Dept *)[_deptList objectAtIndex:index] deptShortName];
}

- (UIColor *)barChart:(SimpleBarChart *)barChart colorForBarAtIndex:(NSUInteger)index
{
	return [_barColors objectAtIndex:_currentBarColor];
}

@end
